package com.liang.log;

import java.io.File;
import java.io.FileWriter;
import java.util.Calendar;
import java.util.Locale;

/**
 * 日志记录类
 * @author pjt
 *
 */
public class Log {

	private static boolean log;

	private static boolean debug;

	private static String logPath = "/log";

	
	public Log(boolean recordLog){
		log = recordLog;
	}
	public void setDebug(boolean debug) {
		Log.debug = debug;
	}

	public void setLog(boolean log) {
		Log.log = log;
	}

	public static void info(Object obj) {
		System.out.println(getTimer() + " INFO:\t" + obj);
	}

	public static void log(Throwable throwable) {
		if (log) {
			String logStr = getTimer() + ": " + throwable.getLocalizedMessage();
			System.out.println("LOG:\t" + logStr);
		}
	}

	public static void debugDetailed(Throwable logThrow, Object obj) {
		if (debug) {
			StackTraceElement[] elem = logThrow.getStackTrace();
			System.out.println(getTimer() + "\tDEBUG Detailed:\t"+elem[0].getClassName()
					+'.'+ elem[0].getMethodName() + "\t"
					+ obj.toString());
		}
	}

	private static String getTimer() {

		Calendar calender = Calendar.getInstance(Locale.CHINA);
		StringBuffer timeBuffer = new StringBuffer();

		timeBuffer.append(calender.get(Calendar.YEAR)).append('-').append(
				calender.get(Calendar.MONTH) + 1).append('-').append(
				calender.get(Calendar.DAY_OF_MONTH)).append(' ').append(
				calender.get(Calendar.HOUR_OF_DAY)).append(':').append(
				calender.get(Calendar.MINUTE)).append(':').append(
				calender.get(Calendar.SECOND));

		return timeBuffer.toString();

	}

	private static void writeLog(String logStr) throws Exception {
		File logdir = new File(logPath);
		if (!logdir.exists()) {
			logdir.createNewFile();
		}
		File log = new File(logdir.getPath() + "/" + getTimer() + ".log");
		FileWriter fw = new FileWriter(log);
		fw.write(logStr);
		fw.close();
	}
}
